package com.itwelkin.ssm.controller;

import com.itwelkin.ssm.mapper.AdminMapper;
import com.itwelkin.ssm.model.Admin;
import com.itwelkin.ssm.service.AdminService;
import com.itwelkin.ssm.system.SysException;
import com.itwelkin.ssm.utils.SystemUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class DemoController {
    private AdminService adminService;

    public DemoController(AdminService adminService) {
        this.adminService = adminService;
    }

    @RequestMapping("loginController")
    public String userList(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        //封装参数
        Admin admin = new Admin();
        Map<String,String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.populate(admin,parameterMap);
        }catch (Exception e){
            e.printStackTrace();
        }
        //进行验证码判断 数据回显
        if(SystemUtils.checkVerify(request,"adminUser",admin)==null){
            return "http://localhost:8080/ssm_biao7/user/deng.jsp";
        }
        //处理业务逻辑
        Admin queryAdmin = null;
        //SystemUtils.sendMail("aaa@itwelkin.com", UUID.randomUUID().toString().replace("-","")+UUID.randomUUID().toString().replace("-",""));
        try {
            queryAdmin = adminService.login(admin);
        }catch (SysException e){
            session.setAttribute("msg",e.getMessage());
            session.setAttribute("adminUser",admin);
            return "http://localhost:8080/ssm_biao7/user/deng.jsp";
        }
        //没有用户名或账号密码不匹配，queryAdmin为空
        if(queryAdmin==null){
            session.setAttribute("msg","对不起您的账号或密码错误");
            return "http://localhost:8080/ssm_biao7/user/deng.jsp";
        }

        //到处说明没问题，重定向在session中存储账号信息
        request.getSession().setAttribute("adminUser",queryAdmin);
        //判断是否是admin
        if(queryAdmin.getUsername().equalsIgnoreCase("admin")){
            return "http://localhost:8080/ssm_biao7/user/info.jsp";
        }else {
            return "http://localhost:8080/ssm_biao7/customer/customerlist";
        }
    }

    @RequestMapping("registryController")
    public String registryController(HttpSession session, HttpServletRequest request){
        Admin admin = new Admin();
        Map<String,String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.populate(admin,parameterMap);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(admin);
        //进行验证码判断 数据回显
        if(SystemUtils.checkVerify(request,"adminUser",admin)==null){
            return "http://localhost:8080/ssm_biao7/user/zhu.jsp";
        }
        //尝试进行注册
        try{
            adminService.registry(admin);
        }catch (SysException e){
            session.setAttribute("msg",e.getMessage());
            session.setAttribute("adminUser",admin);
            return "http://localhost:8080/ssm_biao7/user/zhu.jsp";
        }
        session.setAttribute("msg","请登录邮箱激活");
        return "http://localhost:8080/ssm_biao7/user/deng.jsp";
    }

    @RequestMapping("active")
    public void activeController(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        String code = request.getParameter("code");
        Admin adminUser = null;

        try {
            adminUser = adminService.activeAdminUser(code);
            if (adminUser == null){
                session.setAttribute("msg","对不起,该链接已失效,请联系管理员");
            }else {
                session.setAttribute("msg","恭喜您激活成功,请联系管理员授权");
                session.setAttribute("adminUser",adminUser);
            }
        }catch (SysException e){
            session.setAttribute("msg",e.getMessage());
        }
        request.getRequestDispatcher("/user/deng.jsp").forward(request,response);
    }

    @RequestMapping("list")
    public void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        if(SystemUtils.checkSession(request,response,true)){return;}
        //查询所有管理员信息
        List<Admin> admins = adminService.queryUserList();
        //传数据到前台
        request.setAttribute("adminUsers",admins);
        request.getRequestDispatcher("/user/adminlist.jsp").forward(request,response);
    }

    @RequestMapping("resendEmail")
    public void resendEmail(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        if(SystemUtils.checkSession(request,response,true)){return;}

        String id = request.getParameter("id");
        try {
            adminService.resendMail(id);
        } catch (SysException e) {
            SystemUtils.checkOperation(request,response,e);
            return;
        }
        response.sendRedirect(request.getContextPath()+"/user/list");
    }
    @RequestMapping("resendWithMore")
    public void resendEmailWithMore(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        if(SystemUtils.checkSession(request,response,true)){return;}

        String[] ids = request.getParameterValues("ids");
        boolean result = false;
        try {
            result= adminService.resendMailWithMore(ids);
        } catch (SysException e) {
            SystemUtils.checkOperation(request,response,e);
            return;
        }
        if (result){
            request.setAttribute("msg","批量重发成功");
        }else {
            request.setAttribute("msg","操作不合法");
        }

        request.getRequestDispatcher("/user/list").forward(request,response);
    }


    @RequestMapping("authorize")
    public void authorize(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        if(SystemUtils.checkSession(request,response,true))return;

        String id = request.getParameter("id");
        String opr = request.getParameter("opr");

        try {
            adminService.authorize(id,opr);
        }catch (SysException e){
            SystemUtils.checkOperation(request,response,e);
            return;
        }

        request.setAttribute("msg",opr.equals("0") ? "取消成功":"授权通过");
        request.getRequestDispatcher("/user/list").forward(request,response);
    }

    @RequestMapping("authorizeWithMore")
    public void authorizeWithMore(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        if(SystemUtils.checkSession(request,response,true))return;

        String[] ids = request.getParameterValues("ids");
        boolean result = false;

        try {
            result= adminService.authorizeWithMore(ids);
        } catch (SysException e) {
            SystemUtils.checkOperation(request,response,e);
            return;
        }
        if (result){
            request.setAttribute("msg","批量授权成功");
        }else {
            request.setAttribute("msg","批量授权失败");
        }

        request.getRequestDispatcher("/user/list").forward(request,response);

    }

    @RequestMapping("listWithCondition")
    public void listWithCondition(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        if (SystemUtils.checkSession(request,response,true))return;

        String username = request.getParameter("username");
        String regStart = request.getParameter("regStart");
        String regEnd = request.getParameter("regEnd");

        request.setAttribute("username",username);
        request.setAttribute("regStart",regStart);
        request.setAttribute("regEnd",regEnd);

        List<Admin> admins = adminService.queryUserListWithCondition(username,regStart,regEnd);
        request.setAttribute("adminUsers",admins);
        request.getRequestDispatcher("/user/adminlist.jsp").forward(request,response);
    }
}
